package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SendMsgUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private SendMsgUtils sendMsgUtils;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @PostMapping("/sendMsg")
    public R sendMsg11(@RequestBody User user, HttpServletRequest request) {
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //生成随机的4位验证码
            String yzm = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}", yzm);
            sendMsgUtils.sendMsg(phone, Integer.valueOf(yzm));
            //需要将生成的验证码保存到Session
//            request.getSession().setAttribute(phone, yzm);

            //之前我们保存在了session中，现在我们保存在redis缓存中
            redisTemplate.opsForValue().set(phone,yzm,5, TimeUnit.MINUTES);
            return R.success("验证码发送成功");
        }
      return R.success("发送失败");
    }

    @PostMapping("/sendMsg11")
    public R sendMsg(@RequestBody User user, HttpServletRequest request) {
        /*
        1.先获取电话号码
        2.发送短信获取验证码
        3.生成4为验证码
        4.把验证码保存在session中，因为后面登录时要进行对比
        5.用redis对项目进行优化，缓存短信验证码。
         */
        String phone = user.getPhone();//取出电话号码
        String s = (String) request.getSession().getAttribute("result");
        Integer yzm = ValidateCodeUtils.generateValidateCode(4);
        if (StringUtils.isEmpty(user.getPhone())) {
            return R.error("手机号码为空！");
        }
        if (s == null) {//说明是第一次
            log.info("该手机号码{},的验证码为{}.", phone, yzm);
            long currentTimeMillis = System.currentTimeMillis();//获取当前时间毫秒值
            String result = phone + "_" + currentTimeMillis + "_" + yzm;//包含验证码、电话、时间搓 18282988525_1054_1616516516165
            request.getSession().setAttribute("result", result); //18282988525_1054_1616516516165
            System.out.println("第一次的" + yzm);
//            sendMsgUtils.sendMsg(phone, yzm);
            return R.success("手机验证码短信发送成功!");
        }
        String str[] = s.split("_");
        String sessionTime = str[1];//拿到第一次的时间
        long hh = System.currentTimeMillis();
        long l = hh - Long.valueOf(sessionTime);//查值
        System.out.println(l);
        if (l > 60000) {
            log.info("该手机号码{},的验证码为{}.", phone, yzm);
            System.out.println("发送验证码" + yzm);
//            sendMsgUtils.sendMsg(phone, yzm);
            request.getSession().removeAttribute("result");//清除第一次时间
            /*
            重新拼接
             */
            long currentTimeMillis = System.currentTimeMillis();//获取当前时间毫秒值
            String yzmTime = phone + "_" + currentTimeMillis + "_" + yzm;//包含验证码的时间搓 1054_1616516516165
            request.getSession().setAttribute("result", yzmTime); // 18282988525 1054_1616516516165
            return R.success("手机验证码短信发送成功!");
        } else {
            return R.error("请勿重复发送");
        }
    }

    @PostMapping("/login")
    public R login(HttpServletRequest request, @RequestBody Map map) {
        /*
        1.接收到phone，code，并取出
        2.根据页面传递的phone拿到浏览器中的session的值，然后进行验证码比对
        3.如果验证码相同则登录成功，不相同则失败。
               相同的话就注册用户，并在数据库中保存
         */

        String code = map.get("code").toString();
        String phone = map.get("phone").toString();

//        String result = (String) request.getSession().getAttribute("result");
//        String sYzm = result.split("_")[2];

//        String sYzm = (String) request.getSession().getAttribute(phone);

        String sYzm = redisTemplate.opsForValue().get(phone);
        if (sYzm != null && sYzm.equals(code)) {
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone, phone);
            User user = userService.getOne(lqw);
            if (user == null) {
                user = new User();
                user.setStatus(1);
                user.setPhone(phone);
                userService.save(user);
            }
            redisTemplate.delete(phone);
            request.getSession().setAttribute("user", user.getId());
            return R.success(user);
        }

        return R.success("登录失败！");
    }

    @PostMapping("/loginout")
    public R loginout(HttpServletRequest request) {
        request.removeAttribute("user");
        return R.success(null);
    }


}
